package com.zhitongyun.devlop.db;

import android.os.Environment;

import com.zhitongyun.devlop.db.migration.DBMainMigration;
import com.zhitongyun.devlop.db.model.DBMainLibraryModle;

import java.io.File;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.exceptions.RealmMigrationNeededException;

/**
 * 处理数据库更新
 * Created by huanglei on 6/14/16.
 */
public class DBHelper {

    public static final String DB_DIR = "daatabases";
    public static final String ROOT_DIR = "haleyplugin";
    public static final String DB_NAME = "main.realm";

    public static String getDBPath() {
        File dir = Environment.getExternalStorageDirectory();
        return dir.getPath() + File.separator
                + ROOT_DIR + File.separator
                + DB_DIR + File.separator;
    }

    /**
     * 获取realm对象句柄
     *
     * @return
     */
    public static Realm createMainDatabases() {
        String dataBaseDir = getDBPath();
        File file = new File(dataBaseDir);
        if (!file.exists()) {
            file.mkdirs();
        }


        RealmConfiguration examBookConfig;
        examBookConfig = new RealmConfiguration.Builder(file)
                .name(DB_NAME)
                .modules(new DBMainLibraryModle())
                .migration(new DBMainMigration())
                .build();

        try {
            return Realm.getInstance(examBookConfig);
        } catch (RealmMigrationNeededException e) {
            e.printStackTrace();
            return null;
        }

    }

}
